const { logInfo, getFileList, parseFile, readFileContent, writeJsonFile, processTemplate, hasChinese, processJs } = require("./utils");
const { writeFileSync } = require("node:fs");
const { whitelistDirs, whitelistFiles, CONFIG } = require("./config");
const GoGoCode = require("gogocode");

logInfo('开始处理vue文件模板部分，请耐心等待...')

const fileList = getFileList(CONFIG.FILE_TYPES);
logInfo(`共找到 ${fileList.length} 个文件`);
fileList.forEach((file) => {
  const path = file.replaceAll('\\', '/');
  if (whitelistDirs && whitelistDirs.some(dir => path.includes(dir))) {
    return
  }
  if (whitelistFiles && whitelistFiles.includes(path)) {
    return
  }
  if (path.includes(".min.js")) {
    return
  }
  const content = readFileContent(file);
  logInfo(`正在处理: ${file}`);
  const ext = path.split(".").pop();
  if (ext === 'vue') {
    if (hasChinese(content)) {
      const newContent = content.replace(/<template>([\s\S]*)<\/template>/, match => {
        return processTemplate(match)
      })
        .replace(/<script>[\s\S]*?<\/script>/, (match) => {
          const script = match.replace(/<script>/, "").replace(/<\/script>/, "")
          return `<script>\r\n${processJs(script, file)}\r\n</script>`
        })
      writeFileSync(file, newContent);
      logInfo(`已处理并写入: ${file}`);
    }
  } else {
    const code = processJs(content, file)
    writeFileSync(file, code);
    logInfo(`已处理并写入: ${file}`);
  }
})